
import { CancellationToken, WebviewView, WebviewViewProvider, WebviewViewResolveContext, Uri, Webview, ExtensionContext } from "vscode";
import * as fs from "fs";
import * as path from "path";
import { getFanyi } from "./api";

interface Message {
  type: string
  data?: string | any[]
}
export class ViewPanle implements WebviewViewProvider {
  private _extensionUri:Uri;
  // @ts-ignore
  private _webviewView:WebviewView;
  constructor(private _context:ExtensionContext){
    this._extensionUri = _context.extensionUri;
  }
  resolveWebviewView(webviewView: WebviewView, context: WebviewViewResolveContext, token: CancellationToken) {
    this._webviewView = webviewView;
    
    webviewView.webview.options = {
      enableScripts: true,
      localResourceRoots: [
        Uri.joinPath(this._extensionUri,'webui')
      ]
    };
    webviewView.webview.html= this._readHtml(webviewView.webview);
    webviewView.webview.onDidReceiveMessage(async ({type,data})=>{
      switch (type) {
        case 'fetch':
          const res = await getFanyi(data);
          this.postMessage({ type: 'dsc', data: res});
          break;
        default:
          break;
      }
    });
  }

  private _readHtml = (webview: Webview) => {
    const nonce = getNonce();
    const url = path.join(this._context.extensionPath,'webui','index.html');
    const html =  fs.readFileSync(url, 'utf8');
    let formatUrl = html.replace(/(<link.+?href="|<script.+?src="|<img.+?src=")(.+?)"/g,(m,s1,s2)=>{
      return s1 + webview.asWebviewUri(Uri.joinPath(this._extensionUri, 'webui', ...s2.split('/'))).toString() + '"';
    });
    formatUrl = formatUrl.replace('${webview.cspSource}',webview.cspSource);
    formatUrl = formatUrl.replace(/\${nonce}/g,nonce);
    return formatUrl;
  };

  public postMessage(param:Message){
    this._webviewView.webview.postMessage(param);
  }

  public openView(){
    this._webviewView.show();
  }
  
}

function getNonce() {
	let text = '';
	const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	for (let i = 0; i < 32; i++) {
		text += possible.charAt(Math.floor(Math.random() * possible.length));
	}
	return text;
}


